package com.hmdp;

import com.hmdp.entity.Shop;
import com.hmdp.service.IShopService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;

/**
 * @program: hm-dianping
 * @description:
 * @author: Feng
 * @create: 2023-03-18 07:11
 **/

@SpringBootTest
public class SaveShopInRedisWithTypeid {
    @Autowired
    private IShopService shopService;
    @Autowired
//    是stringRedisTemplate 而且idea有给提示
    private StringRedisTemplate redisTemplate;

    @Test
    void save() {
        //查询所有shop
        List<Shop> shops = shopService.query().list();
        //获取shop的id，和x，y
        Map<Long, List<Shop>> map = shops.stream().collect(Collectors.groupingBy(Shop::getTypeId));
//        遍历map获取key和value，再遍历value获取id和x，y存入redis
//        map.entrySet.for
        for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
            //        这个泛型是member的类型
            List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>();
            String key = SHOP_GEO_KEY + entry.getKey();
            for (Shop shop : entry.getValue()) {
//                每次都要与数据库连接，浪费性能
//                redisTemplate.opsForGeo().add(key, new Point(shop.getX(),shop.getY()),shop.getId().toString());
                locations.add(new RedisGeoCommands.GeoLocation<>(shop.getId().toString(),new Point(shop.getX(),shop.getY())));
            }
//            批量添加
            redisTemplate.opsForGeo().add(key, locations);

        }
    }
}
